import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../../large_data/CV2/lesson/Day07'
# img_name = 'hammer.jpg'
img_name = 'Moscow.jpeg'
# img_dir = '../../../../../large_data/pic'
# img_name = 'DSC05039.JPG'
# img_name = 'DSC05022_1.JPG'
# img_name = 'dog.jpg'
# img_name = 'dog_bird.jpg'
# img_name = 'football.jpg'
# img_name = 'messi5.jpg'
img_path = os.path.join(img_dir, img_name)

spr = 2
spc = 5
spn = 0
plt.figure(figsize=[14, 6])

sep('load')
img = cv.imread(img_path, cv.IMREAD_GRAYSCALE)
img_bgr = cv.imread(img_path, cv.IMREAD_COLOR)
# img = cv.resize(img, None, fx=0.1, fy=0.1, interpolation=cv.INTER_CUBIC)
print('original shape', img.shape)
H, W = img.shape
H2 = (H - 1) // 2
W2 = (W - 1) // 2
my_show_img(img, 'original', cmap='gray')

# hist by plt of gray
spn += 1
plt.subplot(spr, spc, spn)
plt.hist(img.ravel(), 256, [0, 256])
plt.title('hist by plt')

# hist by cv of gray
spn += 1
sep('hist by cv of gray')
plt.subplot(spr, spc, spn)
hist = cv.calcHist([img], [0], None, [256], [0, 256])
print_numpy_ndarray_info(hist, 'hist')
plt.plot(hist)
plt.title('hist by cv')

# hist by np of gray
sep('hist by np of gray')
spn += 1
plt.subplot(spr, spc, spn)
hist, bins = np.histogram(img.ravel(), 256, [0, 256])
print_numpy_ndarray_info(hist, 'hist')
plt.plot(hist)
plt.title('hist by np')

# colorful ori
my_show_img(img_bgr, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGBA))

# hist for channels
sep('hist by np of color')
spn += 1
plt.subplot(spr, spc, spn)
colors = ['b', 'g', 'r']
for i, col in enumerate(colors):
    hist = cv.calcHist([img_bgr], [i], None, [256], [0, 256])
    plt.plot(hist, color=col)
    plt.xlim([0, 256])

